//
//  MineDoLikeListViewController.m
//  ShowYork
//
//  Created by hxh on 2020/11/13.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "MineCommentListViewController.h"
#import "HomePageDetailViewController.h"
#import "MineCommentCell.h"
#import "MineMessageItemModel.h"
#import "CommonWebViewController.h"
#import "CampusQuestionDetailViewController.h"
#import "VoiceReadItemDetailViewController.h"
#import "DFPlayer.h"
@interface MineCommentListViewController ()<UITableViewDelegate,UITableViewDataSource,MineCommentCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,assign)NSInteger pageIndex;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)UILabel *noDataMainTitleLb;
@property (nonatomic,strong)UILabel *noDataSubTitleLb;
@property (nonatomic,strong)UIView *line;
@property (nonatomic,strong)MineMessageItemModel *messageModel;
@end

@implementation MineCommentListViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
 
    UIImageView *navLine = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    navLine.hidden = YES;

}



- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    UIImageView *navLine = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    navLine.hidden = NO;
}


- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    // Do any additional setup after loading the view.
}

- (void)setUI{
    self.navigationItem.title = @"评论";
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    self.line = [[UIView alloc]init];
    self.line.backgroundColor = RGBA(230, 230, 230, 230);
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(0.5);
    }];

    self.tableView.backgroundColor = [UIColor whiteColor];
    
    __weak typeof(self)weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pageIndex = 1;
        [weakSelf loadDataSource];
    }];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageIndex++;
        [weakSelf loadDataSource];
    }];
    

    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.tableView.mj_header = header;
    self.tableView.mj_footer = footer;
    
    self.pageIndex = 1;
    
    [self.tableView.mj_header beginRefreshing];
    
    self.noDataMainTitleLb = [[UILabel alloc]init];
    self.noDataMainTitleLb.text = @"你还没有被评论哦";
    self.noDataMainTitleLb.textColor = C51;
    self.noDataMainTitleLb.font = font(12);
    [self.view addSubview:self.noDataMainTitleLb];
    
    self.noDataSubTitleLb = [[UILabel alloc]init];
    self.noDataSubTitleLb.text = @"赶快去和好友互动起来吧";
    self.noDataSubTitleLb.textColor = RGBA(107, 111, 122, 1);
    self.noDataSubTitleLb.font = font(12);
    [self.view addSubview:self.noDataSubTitleLb];
    
    [self.noDataMainTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).offset(-kNavBarHeight);
    }];
    [self.noDataSubTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.noDataMainTitleLb.mas_bottom);
    }];
    self.noDataMainTitleLb.hidden = YES;
    self.noDataSubTitleLb.hidden = YES;    
}

- (void)back{
    [super back];
}

- (void)requestData{
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadDataSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"messageType"] = @3;
    param[@"pageIndex"] = @(self.pageIndex);
    param[@"pageSize"] = @10;
    param[@"md5"] = [RPAppManager md5StrWithApi:MessageList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(MessageList) parames:param success:^(id responseObj) {
        if (self.pageIndex == 1) {
            self.dataArray = [MineMessageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
            [self.tableView.mj_footer resetNoMoreData];
        }else{
            [self.dataArray addObjectsFromArray:[MineMessageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        self.tableView.mj_footer.hidden = self.dataArray.count == 0;
        CGFloat bottom = self.tableView.mj_insetB;
        if ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                self.tableView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            if (self.tableView.mj_footer.cl_height == 138.0f) {
                self.tableView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.tableView.mj_insetB = 44.0f;
                }
            }
        }
        self.noDataSubTitleLb.hidden = self.dataArray.count != 0;
        self.noDataMainTitleLb.hidden = self.dataArray.count != 0;
        
        [self.tableView reloadData];
        
        __block NSInteger maxCount = 0;
        [self.dataArray enumerateObjectsUsingBlock:^(MineMessageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.unread.intValue == 0) {
                maxCount++;
            }
        }];
        NSInteger totalCount = [[[NSUserDefaults standardUserDefaults] objectForKey:@"messageUnReadCount"] intValue];
        if (totalCount >= maxCount) {
            totalCount -= maxCount;
            [[NSUserDefaults standardUserDefaults] setObject:@(totalCount) forKey:@"messageUnReadCount"];
            [[NSUserDefaults standardUserDefaults]synchronize];
        }
    } failure:^(NSError *error) {
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        self.pageIndex--;
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
   
    if (!decelerate) {
        __block BOOL isAllRead = YES;
        NSArray *indexPathArray = [self.tableView indexPathsForVisibleRows];
        [self.dataArray enumerateObjectsUsingBlock:^(MineMessageItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [indexPathArray enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull indexPath, NSUInteger subIndex, BOOL * _Nonnull stop) {
                if (idx == indexPath.row) {
                    if (obj.unread.intValue == 0) {
                        isAllRead = NO;
                    }
                    obj.unread = @1;
                }
            }];
        }];
        if (!isAllRead) {
            if (indexPathArray.count != 0) {
                [self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
            }
        }
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    __block BOOL isAllRead = YES;
    NSArray *indexPathArray = [self.tableView indexPathsForVisibleRows];
    [self.dataArray enumerateObjectsUsingBlock:^(MineMessageItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [indexPathArray enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull indexPath, NSUInteger subIndex, BOOL * _Nonnull stop) {
            if (idx == indexPath.row) {
                if (obj.unread.intValue == 0) {
                    isAllRead = NO;
                }
                obj.unread = @1;
            }
        }];
    }];
    if (!isAllRead) {
        if (indexPathArray.count != 0) {
            [self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    self.tableView.mj_footer.hidden = self.dataArray.count == 0;
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MineCommentCell *cell = [MineCommentCell cellWithTableView:tableView];
    [cell setModel:self.dataArray[indexPath.row]];
    cell.delegate = self;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleDefault) title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        MineMessageItemModel *itemModel = self.dataArray[indexPath.row];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"messageId"] = itemModel.id;
        param[@"md5"] = [RPAppManager md5StrWithApi:UpdateMessageState];
        param[@"status"] = @1;
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UpdateMessageState) parames:param success:^(id responseObj) {
            [self.dataArray removeObjectAtIndex:indexPath.row];
            [self.tableView deleteRow:indexPath.row inSection:0 withRowAnimation:UITableViewRowAnimationAutomatic];
            
        } failure:^(NSError *error) {
            [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        }];
    }];
    return @[deleteAction];
}

#pragma mark - MineCommentCellDelegate

- (void)showUserInfoById:(NSNumber *)userId{
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"userId":userId,@"loadType":@(1)} completion:nil];
}

- (void)showCommentOrReplyByItemModel:(MineMessageItemModel *)itemModel{
    self.messageModel = itemModel;
    // 问题详情
    if (itemModel.contentType.intValue == 5) {
        [self showDataLoadState];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"id"] = itemModel.postId;
        param[@"md5"] = [RPAppManager md5StrWithApi:SchoolQuestionDetail];
        [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolQuestionDetail) parames:param success:^(id responseObj) {
            [self hideDataLoadLoadState];
            CampusQuestionDetailViewController *vc = [[CampusQuestionDetailViewController alloc]init];
            vc.questionId = itemModel.postId;
            if (itemModel.commentState.intValue != 1) {
                vc.targetAnswerId = itemModel.commentId;
            }
            [self.navigationController pushViewController:vc animated:YES];
        } failure:^(NSError *error) {
            [self hideDataLoadLoadState];
            [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        }];
    }else if (itemModel.contentType.intValue == 6){
        [self showDataLoadState];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"id"] = itemModel.postId;
        param[@"md5"] = [RPAppManager md5StrWithApi:VoiceDetails];
        [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(VoiceDetails) parames:param success:^(id responseObj) {
            [self hideDataLoadLoadState];
            VoiceReadItemDetailViewController *dtlVC = [[VoiceReadItemDetailViewController alloc]init];
            dtlVC.commentId = itemModel.commentId;
            dtlVC.isCenterMessage = YES;
            dtlVC.voiceId = itemModel.postId;
            dtlVC.webUrl = [NSString stringWithFormat:@"%@media/audio?id=%@&isApp=true",HtmlUrl,itemModel.id];
            NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:dtlVC];
            [self presentViewController:nav animated:YES completion:nil];
        } failure:^(NSError *error) {
            [self hideDataLoadLoadState];
            [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        }];
    }else{
        if (itemModel.targetUrl.length != 0) {
            if ([itemModel.targetUrl hasPrefix:@"https://"] || [itemModel.targetUrl hasPrefix:@"http://"]) {
                CommonWebViewController *webVC = [[CommonWebViewController alloc]init];
                NSString *url = itemModel.targetUrl;
                NSRange range = [url rangeOfString:@"?"];
                if (range.location != NSNotFound) {
                    if ([url containsString:@"isApp=true"]) {
                        url = [NSString stringWithFormat:@"%@&userId=%@&commentId=%@",url,[RPAppManager getCustomerId],itemModel.commentId];
                    }else{
                        url = [NSString stringWithFormat:@"%@&isApp=true&userId=%@&commentId=%@",url,[RPAppManager getCustomerId],itemModel.commentId];
                    }
                }else{
                    url = [NSString stringWithFormat:@"%@?isApp=true&userId=%@&commentId=%@",url,[RPAppManager getCustomerId],itemModel.commentId];
                }
                webVC.isDark = YES;
                webVC.webUrl = url;
                [self.navigationController pushViewController:webVC animated:YES];
            }
        }else{
            XHPageDetailPlatformType platformType = 0;
            NSNumber *commentId = @0;
            NSNumber *replyId = @0;
            // 评论动态
            if (itemModel.messageType.intValue == 3) {
                platformType = XHPageDetailPlatformTypeMessageComment;
                commentId = itemModel.commentId;
            }
            // 回复
            if (itemModel.messageType.intValue == 4) {
                platformType = XHPageDetailPlatformTypeMessageReply;
                replyId = itemModel.commentId;
            }
            if (itemModel.commentState.intValue == 1) {
                platformType = XHPageDetailPlatformTypeMessageOther;
            }
            [self loadDetailSourceByPostId:itemModel.postId commentId:commentId replyId:replyId platformType:platformType];
        }
    }
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
- (void)loadDetailSourceByPostId:(NSNumber *)postId commentId:(NSNumber *)commentId replyId:(NSNumber *)replyId platformType:(XHPageDetailPlatformType)platformType{
    
    [self showDataLoadState];
    
    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    parma[@"userId"] = [RPAppManager getCustomerId];
    parma[@"postId"] = postId;
    parma[@"md5"] = [RPAppManager md5StrWithApi:GetNewPostDetail];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetNewPostDetail) parames:parma success:^(id responseObj) {
        [self hideDataLoadLoadState];
        NSArray *resultArray = @[[HomePageItemModel mj_objectWithKeyValues:responseObj[RESPONSE]]];
        
        
        HomePageItemModel *itemModel = resultArray.firstObject;
       
        if ([itemModel.deleted boolValue]) {
            if (self.messageModel.contentType.intValue == 2) {
                [WHToast showMessage:@"该作品已删除" duration:2 finishHandler:nil];
            }
            if (self.messageModel.contentType.intValue == 1) {
                [WHToast showMessage:@"该动态已删除" duration:2 finishHandler:nil];
            }
            return;
        }
        
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[kXHListSource] = resultArray;
        param[kXHPlatformType] = @(platformType);
        param[kXHDetailCommentId] = commentId;
        param[kXHDetailReplyId] = replyId;
        param[kXHShowUserInfo] = @(YES);
        param[kXHScrollUnEnable] = @(YES);
        param[kXHItemType] = @(XHPageDetailItemTypeMix);
    
        HomePageDetailViewController *dtlVC = [[HomePageDetailViewController alloc]initWithConfigInfo:param];
    
        [self.navigationController pushViewController:dtlVC animated:YES];
        
    } failure:^(NSError *error) {
        [self hideDataLoadLoadState];
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

-(void)dealloc{
  
}



@end
